<?php

class Book_AdminLevelController extends Core_Controller_Action_Admin {

    public function indexAction() {
        //menu
        $this->view->navigation = $navigation = Engine_Api::_()->getApi('menus', 'core')
                ->getNavigation('book_admin_main', array(), 'book_admin_main_level');

        // Get level id
        if (null !== ($id = $this->_getParam('id'))) {
            $level = Engine_Api::_()->getItem('authorization_level', $id);
        } else {
            $level = Engine_Api::_()->getItemTable('authorization_level')->getDefaultLevel();
        }

        if (!$level instanceof Authorization_Model_Level) {
            throw new Engine_Exception('missing level');
        }

        $id = $level->level_id;

        // Make form
        $this->view->form = $form = new Book_Form_Admin_Settings_Level(array(
            'public' => ( in_array($level->type, array('public')) ),
            'moderator' => ( in_array($level->type, array('admin', 'moderator')) ),
        ));
        $form->level_id->setValue($id);

        // Populate values
        //set values permission
        $permissionsTable = Engine_Api::_()->getDbtable('permissions', 'authorization');

        // Check post
        if (!$this->getRequest()->isPost()) {
            return;
        }

        // Check validitiy
        if (!$form->isValid($this->getRequest()->getPost())) {
            return;
        }

        // Set permissions
        $values = $form->getValues();
        $permissionsTable->setAllowed('book', $id, $values);

        $form->addNotice('Your changes have been saved.');
    }

}
